package Controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"hr-system/Global"
	"hr-system/Model"
	response "hr-system/Response"
	"log"
	"time"
)

type IProbationEmployeeController interface {
	RestController
}

type ProbationEmployeeController struct {
	DB *gorm.DB
}

func NewProbationEmployeeController() IProbationEmployeeController{
	db := Global.GetDB()
	return ProbationEmployeeController{DB: db}
}

func (p ProbationEmployeeController) PageList(c *gin.Context) {
	var requestEmployee Model.Employee
	_ = c.ShouldBind(&requestEmployee)
	name := requestEmployee.Name
	if name != ""{
		var selectEmployee []Model.ProbationEmployee
		// 查询
		result := p.DB.Model(&selectEmployee).Where("name=? and result=[转正,延期]", name).
			Find(&selectEmployee).RowsAffected
		if result == 0 {
			response.Fail(c, "查无相关记录", nil)
			return
		}
	}
	var records []Model.ProbationEmployee
	p.DB.Where("result=[转正,延期]").Order("id").Find(&records)
	re := make([]Model.ReturnProbation, 0)
	length := len(records)
	for i:= 0; i<length; i++ {
		record := records[i]
		var temp Model.Employee
		p.DB.Where("id=?", record.Id).First(&temp)
		if name != "" {
			if name != temp.Name {
				continue
			}
		}
		re = append(re, Model.ReturnProbation{
			UniProbation: record.UniProbation,
			Name: temp.Name,
			DealDate: record.DealDate.Format("2006-01-02"),
		})
	}

	response.Success(c, gin.H{"data": re}, "查询成功")
}

func (p ProbationEmployeeController) Create(c *gin.Context) {
	var requestEmployee Model.ProbationAPI
	_ = c.ShouldBind(&requestEmployee)
	log.Println(requestEmployee)
	updateEmployee := Model.Employee{}
	result := p.DB.Where("id=?",requestEmployee.Id).First(&updateEmployee).RowsAffected
	if result == 0 {
		response.Fail(c, "该员工不存在", nil)
		return
	}
	if updateEmployee.IsQuit == "是" {
		response.Fail(c, "该员工已离职", nil)
		return
	}
	if updateEmployee.IsProbation == "否" {
		response.Fail(c, "该员工为正式员工", nil)
		return
	}
	realRequest := Model.ProbationEmployee{
		UniProbation: requestEmployee.UniProbation,
	}
	realRequest.DealDate,_ = time.Parse("2006-01-02",requestEmployee.DealDate)
	log.Println(realRequest)
	err := p.DB.Create(&realRequest).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	if requestEmployee.Result == "延期" {
		delayDate, _ := time.Parse("2006-01-02", requestEmployee.DelayDate)
		err = p.DB.Model(&updateEmployee).Update("probation_end", delayDate).Error
		if err != nil {
			response.Fail(c, err.Error(), nil)
			return
		}
	} else if requestEmployee.Result == "转正" {
		err = p.DB.Model(&updateEmployee).
			Updates(map[string]interface{}{"is_probation": "否", "employment_form": "正式员工"}).Error
		if err != nil {
			response.Fail(c, err.Error(), nil)
			return
		}
	} else {
		err = p.DB.Model(&updateEmployee).Update("is_quit", "是").Error
		if err != nil {
			response.Fail(c, err.Error(), nil)
			return
		}
	}
	response.Success(c, gin.H{"data": realRequest}, "操作成功")
}
